from itsdangerous import TimestampSigner, BadSignature, SignatureExpired
from dynaconf import Dynaconf

# 加载配置
settings = Dynaconf(
    settings_files=['config/config.yaml'],
    environments=True
)

class SecurityUtil:
    """安全工具类，用于数据签名与加密"""
    
    @staticmethod
    def get_signer():
        """获取签名器"""
        return TimestampSigner(str(settings.security.secret_key))
    
    @staticmethod
    def sign_data(data: str) -> str:
        """对数据进行签名
        
        Args:
            data: 要签名的数据
            
        Returns:
            str: 签名后的数据
        """
        signer = SecurityUtil.get_signer()
        return signer.sign(data).decode('utf-8')
    
    @staticmethod
    def unsign_data(signed_data: str, max_age: int = None) -> str:
        """验证签名数据
        
        Args:
            signed_data: 签名数据
            max_age: 最大有效期（秒）
            
        Returns:
            str: 原始数据
            
        Raises:
            SignatureExpired: 签名已过期
            BadSignature: 签名无效
        """
        signer = SecurityUtil.get_signer()
        return signer.unsign(signed_data, max_age=max_age).decode('utf-8')
